/*
 * @Author: AiLjx
 * @Date: 2022-06-30 20:10:46
 * @LastEditors: AiLjx
 * @LastEditTime: 2022-07-01 18:24:35
 */
import { useEffect } from 'react';
import { IndexBar, List, DotLoading } from 'antd-mobile';
import { connect } from 'dva';

interface ICityObj {
  cityId: number;
  name: string;
  pinyin: string;
  isHot: number;
}
interface InewlistItem {
  title: string;
  items: Array<ICityObj>;
}

function City({ history, dispatch, list, loading }: any) {
  console.log(loading);

  useEffect(() => {
    // redux store中city list无数据时dispatch请求数据
    if (list.length === 0) {
      dispatch({
        type: 'city/getCityList',
      });
    } else {
      // redux中city list有数据时使用缓存数据
      console.log('使用City缓存');
    }
  }, []);

  const changeCity = (item: ICityObj) => {
    // 修改store中city state中的状态
    dispatch({
      // 命名空间city下的changeCity
      type: 'city/changeCity',
      payload: {
        cityName: item.name,
        cityId: item.cityId,
      },
    });
    dispatch({
      type: 'cinema/clearList',
    });

    // 跳转页面
    history.push('/cinema');
  };

  return (
    <div style={{ height: window.innerHeight }}>
      <h1>配合dva redux缓存数据</h1>

      {/* 配合dva的loading插件显示加载组件 */}
      {loading && (
        <div style={{ textAlign: 'center', fontSize: 24 }}>
          <DotLoading color="primary" />
        </div>
      )}

      <IndexBar>
        {list.map((group: InewlistItem) => {
          const { title, items } = group;
          return (
            <IndexBar.Panel index={title} title={title} key={title}>
              <List>
                {items.map((item, index) => (
                  <List.Item key={index} onClick={() => changeCity(item)}>
                    {item.name}
                  </List.Item>
                ))}
              </List>
            </IndexBar.Panel>
          );
        })}
      </IndexBar>
    </div>
  );
}
export default connect((state: any) => {
  return {
    list: state.city.list,
    // dva的loading插件，在effect请求发送时loading.global为true，发送后为false
    loading: state.loading.global,
  };
})(City);
